package com.cl.mybatis.learn.day11;

import org.apache.ibatis.mapping.DatabaseIdProvider;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 *
 * 自定义一个数据库标示提供类，实现DatabaseIdProvider接口
 * 
 * @return
 * @author feizhou
 * @since 2020/10/17 20:19
 */
public class MyDatabaseIdProvider implements DatabaseIdProvider {
    Properties p;
    
    @Override
    public void setProperties(Properties p) {
        System.out.println("要设置的属性：" + p);
        // 通过p来设置数据库别名
        this.p = p;
        
    }
    
    @Override
    public String getDatabaseId(DataSource dataSource) throws SQLException {
        Connection conn = dataSource.getConnection();
        //真实数据库名称
        String dbName = conn.getMetaData().getDatabaseProductName();
        //别名
        String dbAlias = "";
        
        Set<Map.Entry<Object, Object>> entries = p.entrySet();
        
        for (Map.Entry<Object, Object> entry : entries) {
            String dbName1 = (String) entry.getKey();
            String dbAlias1 = (String) entry.getValue();
            if (dbName.equals(dbName1)) {
                dbAlias = dbAlias1;
                break;
            }
        }
        
        return dbAlias;
    }
}